﻿using Hospital.API.Dto;
using Hospital.API.HospitalServices.IServices;
using Hospital.Domain;
using Hospital.ErrorCode;
using Hospital.Infrastructrue;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;

namespace Hospital.API.HospitalServices.Services
{
    public class DoctorServices : IDoctorServices
    {
        private readonly IBaseRepository<Doctor> doctorrepository;
        private readonly IBaseRepository<Fan> fanrepository;
        private readonly ILogger<DoctorServices> logger;

        public DoctorServices(IBaseRepository<Doctor> doctorrepository, IBaseRepository<Fan> fanrepository, ILogger<DoctorServices> logger)
        {
            this.doctorrepository = doctorrepository;
            this.fanrepository = fanrepository;
            this.logger = logger;
        }

        public async Task<APIResult<DoctorDto>> GetById(int id)
        {
            try
            {
                // 根据ID获取医生信息
                var doctor = await doctorrepository.Getlist()
                    .Where(d => d.Id == id && !d.IsDeleted)
                    .FirstOrDefaultAsync();
                var result = new APIResult<DoctorDto>();
                if (doctor == null)
                {
                    
                    result.Code = ResultCode.Error;
                    result.Message = "医生不存在";
                    return result;
                }

                // 获取医生粉丝数
                var fanCount = await fanrepository.Getlist()
                    .Where(f => f.DoctorId == id)
                    .CountAsync();

                // 转换为DTO
                var doctorDto = new DoctorDto
                {
                    Id = doctor.Id,
                    Name = doctor.Name,
                    Gender = doctor.Gender,
                    RegistrationTime = doctor.RegistrationTime,
                    Phone = doctor.Phone,
                    Hospital = doctor.Hospital,
                    Department = doctor.Department,
                    Title = doctor.Title,
                    BankCardNumber = doctor.BankCardNumber,
                    Specialty = doctor.Specialty,
                    Introduction = doctor.Introduction,
                    AuditStatus = doctor.AuditStatus,
                    ServiceAudit = doctor.ServiceAudit,
                    Certificates = doctor.Certificates,
                    Photo = doctor.Photo,
                    FanCount = fanCount.ToString()
                };

                result.Data = doctorDto;
                result.Code = ResultCode.Success;
                result.Message = "获取医生信息成功";
                return result;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "获取医生信息失败，医生ID: {DoctorId}", id);
                var result = new APIResult<DoctorDto>();
                result.Code = ResultCode.Error;
                result.Message = "获取医生信息失败: " + ex.Message;
                return result;
            }
        }

        public async Task<APIResult<APIPaging<List<Fan>>>> GetFan(FanQueryDto fanQueryDto)
        {
            try
            {
                // 构建查询条件
                var query = fanrepository.Getlist();

                // 应用查询条件
                if (fanQueryDto.DoctorId > 0)
                {
                    query = query.Where(f => f.DoctorId == fanQueryDto.DoctorId);
                }

                if (!string.IsNullOrEmpty(fanQueryDto.Name))
                {
                    query = query.Where(f => f.Name.Contains(fanQueryDto.Name));
                }

                if (fanQueryDto.CreateTime.HasValue)
                {
                    var createTime = fanQueryDto.CreateTime.Value.Date;
                    query = query.Where(f => f.CreateTime.Date == createTime);
                }

                // 获取总数
                var totalCount = await query.CountAsync();

                // 分页
                var pageIndex = fanQueryDto.PageIndex <= 0 ? 1 : fanQueryDto.PageIndex;
                var pageSize = fanQueryDto.PageSize <= 0 ? 10 : fanQueryDto.PageSize;
                var totalPages = (int)Math.Ceiling((double)totalCount / pageSize);

                // 获取分页数据
                var fans = await query
                    .OrderByDescending(f => f.CreateTime)
                    .Skip((pageIndex - 1) * pageSize)
                    .Take(pageSize)
                    .ToListAsync();

                // 构建分页结果
                var pagingResult = new APIPaging<List<Fan>>
                {
                    TotalCount = totalCount,
                    TotalPages = totalPages,
                    Data = fans
                };

                var result = new APIResult<APIPaging<List<Fan>>>();
                result.Data = pagingResult;
                result.Code = ResultCode.Success;
                result.Message = "获取粉丝列表成功";
                return result;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "获取粉丝列表失败");
                var result = new APIResult<APIPaging<List<Fan>>>();
                result.Code = ResultCode.Error;
                result.Message = "获取粉丝列表失败: " + ex.Message;
                return result;
            }
        }


        public async Task<APIResult<APIPaging<List<DoctorDto>>>> GetList(DoctorQueryDto doctorQueryDto)
        {
            try
            {
                // 构建查询条件
                var query = doctorrepository.Getlist().Where(d => !d.IsDeleted);

                // 应用查询条件
                if (!string.IsNullOrEmpty(doctorQueryDto.Name))
                {
                    query = query.Where(d => d.Name.Contains(doctorQueryDto.Name));
                }

                if (!string.IsNullOrEmpty(doctorQueryDto.Department))
                {
                    query = query.Where(d => d.Department != null && d.Department == doctorQueryDto.Department);
                }

                if (!string.IsNullOrEmpty(doctorQueryDto.Title))
                {
                    query = query.Where(d => d.Title != null && d.Title == doctorQueryDto.Title);
                }

                // 获取总数
                var totalCount = await query.CountAsync();

                // 分页
                var pageIndex = doctorQueryDto.PageIndex <= 0 ? 1 : doctorQueryDto.PageIndex;
                var pageSize = doctorQueryDto.PageSize <= 0 ? 10 : doctorQueryDto.PageSize;
                var totalPages = (int)Math.Ceiling((double)totalCount / pageSize);

                // 获取分页数据
                var doctors = await query
                    .OrderByDescending(d => d.RegistrationTime)
                    .Skip((pageIndex - 1) * pageSize)
                    .Take(pageSize)
                    .ToListAsync();

                // 获取医生粉丝数
                var doctorIds = doctors.Select(d => d.Id).ToList();
                var fanCounts = await fanrepository.Getlist()
                    .GroupBy(f => f.DoctorId)
                    .Select(g => new { DoctorId = g.Key, Count = g.Count() })
                    .ToListAsync();

                var fanCountDict = fanCounts.ToDictionary(f => f.DoctorId, f => f.Count.ToString());

                // 转换为DTO
                var doctorDtos = doctors.Select(d => new DoctorDto
                {
                    Id = d.Id,
                    Name = d.Name,
                    Gender = d.Gender,
                    RegistrationTime = d.RegistrationTime,
                    Phone = d.Phone,
                    Hospital = d.Hospital,
                    Department = d.Department,
                    Title = d.Title,
                    BankCardNumber = d.BankCardNumber,
                    Specialty = d.Specialty,
                    Introduction = d.Introduction,
                    AuditStatus = d.AuditStatus,
                    ServiceAudit = d.ServiceAudit,
                    Certificates = d.Certificates,
                    Photo = d.Photo,
                    FanCount = fanCountDict.ContainsKey(d.Id) ? fanCountDict[d.Id] : "0"
                }).ToList();

                // 构建分页结果
                var pagingResult = new APIPaging<List<DoctorDto>>
                {
                    TotalCount = totalCount,
                    TotalPages = totalPages,
                    Data = doctorDtos
                };
                var result = new APIResult<APIPaging<List<DoctorDto>>>();
                result.Data = pagingResult;
                result.Code = ResultCode.Success;
                result.Message = "获取医生列表成功";
                return result;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "获取医生列表失败");
                var result = new APIResult<APIPaging<List<DoctorDto>>>();
                result.Code = ResultCode.Error;
                result.Message = "获取医生列表失败: " + ex.Message;
                return result;
            }
        }

        /// <summary>
        /// 更新医生审核状态
        /// </summary>
        /// <param name="updateDto">更新审核状态DTO</param>
        /// <returns>更新结果</returns>
        public async Task<APIResult<bool>> UpdateAuditStatus(UpdateDoctorAuditStatusDto updateDto)
        {
            try
            {
                // 根据ID获取医生信息
                var doctor = await doctorrepository.Getlist()
                    .Where(d => d.Id == updateDto.DoctorId && !d.IsDeleted)
                    .FirstOrDefaultAsync();

                if (doctor == null)
                {
                    return new APIResult<bool>
                    {
                        Code = ResultCode.Error,
                        Message = "医生不存在",
                        Data = false
                    };
                }

                // 验证审核状态
                var validAuditStatuses = new[] { "待审核", "审核通过", "审核不通过" };
                var validServiceAuditStatuses = new[] { "待审核", "审核通过", "审核不通过" };

                if (!string.IsNullOrEmpty(updateDto.AuditStatus) && !validAuditStatuses.Contains(updateDto.AuditStatus))
                {
                    return new APIResult<bool>
                    {
                        Code = ResultCode.Error,
                        Message = "无效的审核状态",
                        Data = false
                    };
                }

                

                // 更新审核状态
                if (!string.IsNullOrEmpty(updateDto.AuditStatus))
                {
                    doctor.AuditStatus = updateDto.AuditStatus;
                }

                

                

                

                // 保存到数据库
                await doctorrepository.Update(doctor);

                logger.LogInformation("医生审核状态更新成功，医生ID: {DoctorId}, 审核状态: {AuditStatus}", 
                    updateDto.DoctorId, updateDto.AuditStatus);

                return new APIResult<bool>
                {
                    Code = ResultCode.Success,
                    Message = "审核状态更新成功",
                    Data = true
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "更新医生审核状态失败，医生ID: {DoctorId}", updateDto.DoctorId);
                return new APIResult<bool>
                {
                    Code = ResultCode.Error,
                    Message = "更新审核状态失败: " + ex.Message,
                    Data = false
                };
            }
        }
    }
}
